package info.batcloud.fanli.admin.controller;

import com.taobao.api.ApiException;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.ItemcatsGetRequest;
import com.taobao.api.response.ItemcatsGetResponse;
import info.batcloud.fanli.admin.permission.ManagerPermissions;
import info.batcloud.fanli.admin.permission.annotation.Permission;
import info.batcloud.fanli.core.constants.TaobaoClientConstants;
import info.batcloud.fanli.core.constants.TopAuthConstants;
import info.batcloud.fanli.core.service.SystemSettingService;
import info.batcloud.fanli.core.service.TopService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.inject.Inject;
import java.io.UnsupportedEncodingException;

@Controller
@RequestMapping("/api/top")
public class TopController {

    @Inject
    @Qualifier(TaobaoClientConstants.TAOBAO_CLIENT_ITEM_MANAGEMENT)
    private TaobaoClient taobaoClient;

    @Inject
    @Qualifier(TaobaoClientConstants.TAOBAO_CLIENT_ITEM_TBK)
    private TaobaoClient tbkTaobaoClient;

    @Inject
    private SystemSettingService systemSettingService;

    @Inject
    private TopService topService;

    @GetMapping("/auth")
    @Permission(ManagerPermissions.JD_AUTH_SETTING)
    public String auth() throws UnsupportedEncodingException {

        return "redirect:" + topService.generateAuthUrl(TopAuthConstants.STATE_SYSTEM, "web");
    }

    @GetMapping("/itemCat/list/{parentId}")
    @ResponseBody
    public Object listItemCat(@PathVariable long parentId) throws ApiException {
        ItemcatsGetRequest req = new ItemcatsGetRequest();
        req.setParentCid(parentId);
        ItemcatsGetResponse rsp = taobaoClient.execute(req);
        return rsp.getItemCats();
    }

}
